﻿using System;
using org.se.fs.presenter.IView;
using org.se.fs.presenter.Library;

namespace org.se.fs.presenter.View
{
    public class Login
    {
        private readonly ILogin _view;
        private readonly ITask.IUser _task;
        public event FormEvent.FormEventHandler OnAuthenticate;

        protected void TriggerAuthenticate(FormEvent e)
        {
            if (OnAuthenticate != null)
                OnAuthenticate(this, e);
        }

        public Login(ILogin view) : this(view, new Task.Context.User()) { }

        public Login(ILogin view, ITask.IUser task)
        {
            _view = view;
            _task = task;
        }

        public void Initialize()
        {
            _task.OnGetUserId += TaskOnGetUserId;
            _task.OnFetch += TaskOnFetch;
        }

        void TaskOnFetch(object source, FormEvent e)
        {
            if (!e.IsSuccess)
            {
                // Error Logs here
                TriggerAuthenticate(new FormEvent(e.IsSuccess) { Exception = e.Exception });
                _view.ButtonLoginEnable(true);
                return;
            }
            Config.User = (Domain.User)e.Value;
            TriggerAuthenticate(new FormEvent(e.IsSuccess) { Value = e.Value });
        }

        void TaskOnGetUserId(object source, FormEvent e)
        {
            _view.ButtonLoginEnable(true);
            if (!e.IsSuccess)
            {
                TriggerAuthenticate(new FormEvent(e.IsSuccess) { Exception = e.Exception });
                return;
            }
            var a = (UInt64)e.Value;
            _task.Fetch(new Domain.User { Id = a });
        }

        public void Authenticate()
        {
            if (!Validate())
                return;

            _view.ButtonLoginEnable(false);
            _task.GetUserId(new Domain.User {Username = _view.Username.Trim(), Userpass = _view.Userpass.Trim()});
        }

        private bool Validate()
        {
            if (string.IsNullOrEmpty(_view.Username.Trim()))
            {
                _view.FocusUsername();
                OnAuthenticate(this, new FormEvent(false) { Exception = new Exception("Username field is empty.") });
                return false;
            }

            if (string.IsNullOrEmpty(_view.Userpass.Trim()))
            {
                _view.FocusUserpass();
                OnAuthenticate(this, new FormEvent(false) { Exception = new Exception("Password field is empty.") });
                return false;
            }
            return true;
        }
    }
}
